<template>
  <view class="reset-password-page">
    <view class="header">
      <text class="title">重设密码</text>
    </view>
    
    <view class="form-container">
      <view class="form-item">
        <text class="label">请输入QQ邮箱</text>
        <input 
          class="input" 
          type="text" 
          placeholder="请输入QQ邮箱" 
          v-model="email"
          @input="validateEmail"
        />
        <text class="error" v-if="emailError">{{ emailError }}</text>
      </view>
      
      <view class="form-item">
        <text class="label">请输入邮箱验证码</text>
        <view class="verify-code-group">
          <input 
            class="input verify-input" 
            type="number" 
            placeholder="请输入验证码" 
            v-model="verifyCode"
            @input="validateVerifyCode"
          />
          <button 
            class="get-code-btn" 
            @click="getVerifyCode"
            :disabled="!isEmailValid || countdown > 0"
          >{{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}</button>
        </view>
        <text class="error" v-if="verifyCodeError">{{ verifyCodeError }}</text>
      </view>
      
      <view class="form-item">
        <text class="label">请输入密码</text>
        <input 
          class="input" 
          type="password" 
          placeholder="请设置新密码" 
          v-model="password"
          @input="validatePassword"
        />
        <text class="error" v-if="passwordError">{{ passwordError }}</text>
      </view>
      
      <view class="form-item">
        <text class="label">请确认密码</text>
        <input 
          class="input" 
          type="password" 
          placeholder="请再次输入新密码" 
          v-model="confirmPassword"
          @input="validateConfirmPassword"
        />
        <text class="error" v-if="confirmPasswordError">{{ confirmPasswordError }}</text>
      </view>
      
      <button 
        class="submit-btn" 
        @click="resetPassword"
        :disabled="!formValid"
        :class="{ disabled: !formValid }"
      >重设密码</button>

      <view class="back-login">
        <text class="back-text" @click="goBackToLogin">返回登录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onBeforeUnmount } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import Api from "@/utils/Api.js"

// 表单数据
const email = ref('')
const verifyCode = ref('')
const password = ref('')
const confirmPassword = ref('')

// 错误信息
const emailError = ref('')
const verifyCodeError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')

// 验证码倒计时
const countdown = ref(0)
const timer = ref(null)

// 计算属性
const isEmailValid = computed(() => /^[1-9]\d{4,10}@qq\.com$/i.test(email.value))
const formValid = computed(() => {
  return isEmailValid.value && 
         verifyCode.value.length === 6 && 
         password.value.length >= 6 && 
         password.value === confirmPassword.value
})

// 验证方法
const validateEmail = () => {
  if (!email.value) {
    emailError.value = '请输入QQ邮箱'
  } else if (!isEmailValid.value) {
    emailError.value = '请输入正确的QQ邮箱格式'
  } else {
    emailError.value = ''
  }
}

const validateVerifyCode = () => {
  if (!verifyCode.value) {
    verifyCodeError.value = '请输入验证码'
  } else if (verifyCode.value.length !== 6) {
    verifyCodeError.value = '验证码应为6位数字'
  } else {
    verifyCodeError.value = ''
  }
}

const validatePassword = () => {
  if (!password.value) {
    passwordError.value = '请输入密码'
  } else if (password.value.length < 6) {
    passwordError.value = '密码长度不能少于6位'
  } else {
    passwordError.value = ''
  }
  validateConfirmPassword()
}

const validateConfirmPassword = () => {
  if (!confirmPassword.value) {
    confirmPasswordError.value = '请确认密码'
  } else if (password.value !== confirmPassword.value) {
    confirmPasswordError.value = '两次输入的密码不一致'
  } else {
    confirmPasswordError.value = ''
  }
}

// 获取验证码
const getVerifyCode = async () => {
  if (!isEmailValid.value) {
    uni.showToast({ title: '请输入正确的QQ邮箱', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '发送中...', mask: true })
    
    // 使用字符串拼接方式处理表单数据（兼容小程序环境）
    const formData = `email=${encodeURIComponent(email.value)}`
    
    const res = await new Promise((resolve, reject) => {
      uni.request({
        url: Api.domain + Api.sendResetPasswordCode,
        method: 'POST',
        data: formData,
        header: { 
          'Content-Type': 'application/x-www-form-urlencoded' 
        },
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })

    console.log('验证码发送响应:', res)
    
    if (res.statusCode === 200 && res.data.code === 200) {
      uni.showToast({ title: '验证码已发送至邮箱', icon: 'none' })
      
      // 开始倒计时
      countdown.value = 60
      timer.value = setInterval(() => {
        if (countdown.value <= 0) {
          clearInterval(timer.value)
          return
        }
        countdown.value--
      }, 1000)
    } else {
      throw new Error(res.data?.msg || `发送失败，状态码: ${res.statusCode}`)
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: error.message || '发送验证码失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 重设密码
const resetPassword = async () => {
  if (!formValid.value) return
  
  try {
    uni.showLoading({ title: '正在重设密码...', mask: true })
    
    const params = {
      email: email.value,
      emailCode: verifyCode.value,  // 注意参数名必须与后端一致
      password: password.value     // 注意参数名必须与后端一致
    }

    const res = await new Promise((resolve, reject) => {
      uni.request({
        url: Api.domain + Api.resetPassword,
        method: 'POST',
        data: JSON.stringify(params),  // 确保发送JSON格式
        header: { 
          'Content-Type': 'application/json' 
        },
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })

    if (res.statusCode === 200) {
      if (res.data.code === 200) {
        uni.showToast({ title: '密码重设成功', icon: 'success' })
        setTimeout(goBackToLogin, 1500)
      } else {
        throw new Error(res.data.msg || '重设密码失败')
      }
    } else {
      throw new Error(`请求失败，状态码: ${res.statusCode}`)
    }
  } catch (error) {
    console.error('重设密码失败:', error)
    uni.showToast({ title: error.message || '重设密码失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}
// 返回登录
const goBackToLogin = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.redirectTo({
      url: '/pages/login/login'
    })
  }
}

// 清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<style scoped>
.reset-password-page {
  padding: 20px;
  background: linear-gradient(to bottom, #eaf6ff, #fff);
  min-height: 100vh;
  box-sizing: border-box;
}

.header {
  margin-top: 110px;
  margin-bottom: 40px;
}

.title {
  font-size: 30px;
  font-weight: bold;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.20);
}

.form-item {
  margin-bottom: 20px;
}

.label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.input {
  width: 100%;
  height: 40px;
  padding: 0 10px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.error {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: #f56c6c;
}

.verify-code-group {
  display: flex;
  gap: 10px;
}

.verify-input {
  flex: 1;
}

.get-code-btn {
  width: 100px;
  height: 40px;
  line-height: 40px;
  background-color: #f0f0f0;
  color: #333;
  font-size: 12px;
  border-radius: 4px;
  border: none;
  padding: 0;
}

.get-code-btn:disabled {
  opacity: 0.6;
}

.submit-btn {
  width: 100%;
  height: 44px;
  line-height: 44px;
  background-color: #1276ff;
  color: #fff;
  border-radius: 4px;
  font-size: 16px;
  margin-top: 30px;
  margin-bottom: 30px;
  border: none;
}

.submit-btn:active:not(.disabled) {
  opacity: 0.8;
}

.submit-btn.disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.back-login {
  margin-top: 20px;
  text-align: center;
}

.back-text {
  color: #1276ff;
  font-size: 14px;
  text-decoration: underline;
}
</style>